import sys
import os
from PySide6.QtWidgets import *
from PySide6.QtGui import *
from PySide6.QtCore import *
from PySide6.QtSql import *

class Demo(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent = parent
        self.dbFile=os.path.join(self.parent.getAppDir(),'test.db')
        layout = QVBoxLayout()
        layout.setAlignment(Qt.AlignmentFlag.AlignTop)

        toolBar=QToolBar()

        btn=QPushButton('Load')
        btn.clicked.connect(self.Load)
        toolBar.addWidget(btn)
        layout.addWidget(toolBar)
        
        db=QSqlDatabase().addDatabase("QSQLITE")
        db.setDatabaseName(self.dbFile)
        self.model=QSqlRelationalTableModel(db=db)        

        self.tableView=QTableView()
        self.tableView.setModel(self.model)
        self.tableView.setItemDelegateForColumn(2,QSqlRelationalDelegate(self.tableView))        
        #self.tableView.setSelectionBehavior(QTableView.SelectionBehavior.SelectRows)#行选择
        layout.addWidget(self.tableView)
        self.setLayout(layout)
        
    def Load(self):
        self.model.database().open()
        self.model.setTable('User')
        self.model.setRelation(2,QSqlRelation('City','Id','Name'))#设置外键
        self.model.setHeaderData(2,Qt.Orientation.Horizontal,'City')
        
        self.model.select()
        
        self.model.database().close()
def runDemo(parent):
    wigdet =  Demo(parent)
    return wigdet